package cn.yuanqiao.web.controller.archive.chengguojieshou;

import java.io.File;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.archive.chengguojieshou.domain.Yqdaarticulated;
import cn.yuanqiao.archive.chengguojieshou.domain.YqdaarticulatedLog;
import cn.yuanqiao.archive.chengguojieshou.domain.YqdaarticulatedServerLog;
import cn.yuanqiao.archive.chengguojieshou.service.IYqdaarticulatedService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.poi.ListToExclUtil;

import com.alibaba.fastjson2.JSONObject;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;

/**
 * 挂接Controller
 *
 * @author yuanqiao
 * @date 2023-06-30
 */
@RestController
@RequestMapping("/archive/yqdaarticulated")
public class YqdaarticulatedController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(YqdaarticulatedController.class);

    @Autowired
    private IYqdaarticulatedService bjyqYqdaarticulatedService;

    /**
     * 查询挂接列表
     */
    //@PreAuthorize("@ss.hasPermi('manage:YQDAARTICULATED:list')")
    @Log(title = "客户端挂接记录列表查询",businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(Yqdaarticulated bjyqYqdaarticulated)
    {
        startPage();
        List<Yqdaarticulated> list = bjyqYqdaarticulatedService.selectBjyqYqdaarticulatedList(bjyqYqdaarticulated);
        return getDataTable(list);
    }

    /**
     * 服务器挂接记录列表查询
     * @return
     */
    @Log(title = "服务器挂接记录列表查询",businessType = BusinessType.SELECT)
    @GetMapping("/serverList")
    public TableDataInfo serverList(Yqdaarticulated bjyqYqdaarticulated)
    {
        startPage();
        List<Yqdaarticulated> list = bjyqYqdaarticulatedService.serverList(bjyqYqdaarticulated);
        return getDataTable(list);
    }

    /**
     * 挂接日志详情
     * @param id
     * @return
     */
    @Log(title = "客户端挂接日志详情查询",businessType = BusinessType.SELECT)
    @GetMapping("/articulatedLog")
    public TableDataInfo articulatedLog(String id)
    {
        startPage();
        List<YqdaarticulatedLog> list = bjyqYqdaarticulatedService.getArticulatedLog(id);
        return getDataTable(list);
    }

    /**
     * 服务器挂接完成后查询列表日志
     * @param id
     * @return
     */
    @Log(title = "服务端挂接日志详情查询",businessType = BusinessType.SELECT)
    @GetMapping("/getServerLogList")
    public TableDataInfo getServerLogList(String id)
    {
        startPage();
        List<YqdaarticulatedServerLog> list = bjyqYqdaarticulatedService.getServerLogList(id);
        return getDataTable(list);
    }

    /**
     * 未挂接目录查询
     * @param categoryId
     * @return
     */
    /*@Log(title = "未挂接目录查询",businessType = BusinessType.SELECT)
    @GetMapping("/NotarticulatedList")
    public TableDataInfo NotarticulatedList(@RequestParam("categoryId") Long categoryId)
    {
        List<Map<String,Object>> list = bjyqYqdaarticulatedService.getNotarticulatedList(categoryId);
        return getDataTable(list);
    }*/

    /**
     * 未挂接目录查询
     * @param categoryId
     * @return
     */
    @Log(title = "未挂接目录查询",businessType = BusinessType.SELECT)
    @GetMapping("/NotarticulatedList")
    public TableDataInfo NotarticulatedList(@RequestParam("categoryId") Long categoryId,@RequestParam(name = "type",required = false) Integer type)
    {
        List<Map<String,Object>> list = bjyqYqdaarticulatedService.getNotarticulatedList(categoryId,type);
        return getDataTable(list);
    }

    /**
     * 客户端挂接 上传后保存
     * @param json
     * @return
     */
    @Log(title = "客户端挂接上传后保存",businessType = BusinessType.INSERT)
    @PostMapping("/articulated")
    public AjaxResult articulated(@RequestBody JSONObject json)
    {
        Map<String, Object> articulated = bjyqYqdaarticulatedService.articulated(json);
        return AjaxResult.success(articulated.get("msg"));
    }

    /**
     * 服务器挂接
     * @param json
     * @return
     */
    @Log(title = "服务端挂接保存",businessType = BusinessType.INSERT)
    @PostMapping("/serverArticulated")
    public AjaxResult serverArticulated(@RequestBody JSONObject json)
    {
        String unZipPath = json.getString("unZipPath");
        if(!StringUtils.isNotEmpty(unZipPath)){
            throw new ServiceException("路径不能为空");
        }
        File file = new File(unZipPath);
        if(!file.exists()){
            throw new ServiceException("路径不存在");
        }
        if(!file.isDirectory()){
            throw new ServiceException("请输入文件夹路径");
        }
        //服务器挂接标志
        json.put("articulatedType","server");
        //服务器挂接没传挂接方式 默认根据文件名挂接
        boolean gjfs = json.containsKey("GJFS");
        if(!gjfs){
            json.put("GJFS","NAME");
        }
        Map<String, Object> articulated = bjyqYqdaarticulatedService.articulated(json);
        return AjaxResult.success(articulated);
    }

    /**
     * 导出挂接列表
     */
    //@PreAuthorize("@ss.hasPermi('manage:YQDAARTICULATED:export')")
    @Log(title = "挂接", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Yqdaarticulated bjyqYqdaarticulated)
    {
        List<Yqdaarticulated> list = bjyqYqdaarticulatedService.selectBjyqYqdaarticulatedList(bjyqYqdaarticulated);
        ExcelUtil<Yqdaarticulated> util = new ExcelUtil<Yqdaarticulated>(Yqdaarticulated.class);
        util.exportExcel(response, list, "挂接数据");
    }

    /**
     * 获取挂接详细信息
     */
    //@PreAuthorize("@ss.hasPermi('manage:YQDAARTICULATED:query')")
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") String ID)
    {
        return success(bjyqYqdaarticulatedService.selectBjyqYqdaarticulatedByID(ID));
    }

    /**
     * 新增挂接
     */
    //@PreAuthorize("@ss.hasPermi('manage:YQDAARTICULATED:add')")
    @Log(title = "挂接", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Yqdaarticulated bjyqYqdaarticulated)
    {
        return toAjax(bjyqYqdaarticulatedService.insertBjyqYqdaarticulated(bjyqYqdaarticulated));
    }

    /**
     * 修改挂接
     */
    //@PreAuthorize("@ss.hasPermi('manage:YQDAARTICULATED:edit')")
    @Log(title = "挂接", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Yqdaarticulated bjyqYqdaarticulated)
    {
        return toAjax(bjyqYqdaarticulatedService.updateBjyqYqdaarticulated(bjyqYqdaarticulated));
    }

    /**
     * 删除挂接
     */
    //@PreAuthorize("@ss.hasPermi('manage:YQDAARTICULATED:remove')")
    @Log(title = "挂接", businessType = BusinessType.DELETE)
	@DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable String[] IDs)
    {
        return toAjax(bjyqYqdaarticulatedService.deleteBjyqYqdaarticulatedByIDs(IDs));
    }

    @PostMapping("/exportServerLog")
    @Log(title = "服务器挂接日志导出", businessType = BusinessType.EXPORT)
    public void exportServerLog(HttpServletResponse response,@RequestParam("data1") String data1)
    {
        JSONObject json = JSONObject.parseObject(data1);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        Workbook wb = null;
        try {
            //获取表头以及数据
            String articulated_id = json.getString("id");
            List<String> title = new ArrayList<>(Arrays.asList("文件类型","文件名称","文件大小","上传结果","失败原因"));
            List<YqdaarticulatedServerLog> list = bjyqYqdaarticulatedService.getServerLogList(articulated_id);
            List<List<String>> body = new ArrayList<>();
            if(list!=null && list.size()!=0){
                list.stream().forEach(k->{
                    String docName = k.getDocName();
                    String type = docName.substring(docName.lastIndexOf(".")+1);
                    List<String> list1 = new ArrayList<>();
                    list1.add(type);
                    list1.add(k.getDocName());
                    list1.add(k.getDocFileSize());
                    list1.add(k.getResult());
                    list1.add(StringUtils.isEmpty(k.getFailResult()) || "null".equals(k.getFailResult())?"":k.getFailResult());
                    body.add(list1);
                });
            }
            wb = ListToExclUtil.getWorkbookByListNoDict(title,body,"sheet");
            wb.write(response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
            log.error("导出Excel异常{}", e.getMessage());
        }finally {
            if(wb!=null){
                IOUtils.closeQuietly(wb);
            }
        }
    }
}
